package com.gmics.unifiq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Provider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.gmics.android.R;
import com.gmics.unifiq.controller.CourseFunctions;
import com.gmics.unifiq.controller.DirectionsJSONParser;
import com.gmics.unifiq.controller.JSONParser;
import com.gmics.unifiq.controller.SchoolFunction;
import com.gmics.unifiq.entity.Course;
import com.gmics.unifiq.entity.School;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ComparisonResultActivity extends FragmentActivity implements LocationListener{
	
    //GoogleMap map, map1;
    ArrayList<LatLng> markerPoints;
    TextView distanceTv;
    TextView distanceTv1;
    TextView timeTV;
    TextView timeTV1;
    TextView courseNameTv, courseNameTv1;
    ImageView mapImg, mapImg1;
    TableRow travel, travel1, travel2;
    String mapData, mapData1;
    TextView uniTv, uniTv1;
    TextView schoolTv, schoolTv1;
    TextView entryRecqTv, entryRecqTv1;
    TextView adminScheduleTv, adminScheduleTv1;
    TextView cutOffGpaTv, cutOffGpaTv1;
    TextView gpaPercTv, gpaPercTv1;
    TextView lengthTv, lengthTv1;
    TextView scholarshipTv, scholarshipTv1;
    TextView emailTv, emailTv1;
    TextView phoneTv, phoneTv1;
    TextView feesTv, feesTv1;
    TextView travelTv;
    
    LinearLayout mapContainer;
    
    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
  
    Course c, c1;
    
    School s, s1;
    String courseName;
    String courseName1;
    double lat, lo;
    LatLng start, dest, dest1;
    double startLat, startLon, destLat, destLon;
    double destLat1, destLon1;
    
    String address;
    boolean useCurLoc=false;
    LatLng curLoc;
    
    PolylineOptions polylineOptions, polylineOptions1;
    
    int seq = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comparison_result);
		
		mapContainer = (LinearLayout) findViewById(R.id.map_container);
		travelTv = (TextView) findViewById(R.id.travelTv);
		travel = (TableRow) findViewById(R.id.travelRow);
        travel1 = (TableRow) findViewById(R.id.travelRow1);
        travel2 = (TableRow) findViewById(R.id.travelRow2);
        distanceTv = (TextView) findViewById(R.id.tv_distance);
        distanceTv1 = (TextView) findViewById(R.id.tv_distance1);
        timeTV = (TextView) findViewById(R.id.tv_time);
        timeTV1 = (TextView) findViewById(R.id.tv_time1);
        
         uniTv = (TextView) findViewById(R.id.uniTv); uniTv1 = (TextView) findViewById(R.id.uniTv1);
         schoolTv = (TextView) findViewById(R.id.schoolTv); schoolTv1 = (TextView) findViewById(R.id.schoolTv1);
         entryRecqTv = (TextView) findViewById(R.id.entryRecqTv); entryRecqTv1 = (TextView) findViewById(R.id.entryRecqTv1);
         adminScheduleTv = (TextView) findViewById(R.id.adminScheduleTv); adminScheduleTv1 = (TextView) findViewById(R.id.adminScheduleTv1);
         cutOffGpaTv = (TextView) findViewById(R.id.cutOffGpaTv); cutOffGpaTv1 = (TextView) findViewById(R.id.cutOffGpaTv1);
         gpaPercTv = (TextView) findViewById(R.id.gpaPercTv); gpaPercTv1 = (TextView) findViewById(R.id.gpaPercTv1);
         lengthTv = (TextView) findViewById(R.id.lengthTv); lengthTv1 = (TextView) findViewById(R.id.lengthTv1);
         scholarshipTv = (TextView) findViewById(R.id.scholarshipTv); scholarshipTv1 = (TextView) findViewById(R.id.scholarshipTv1);
         emailTv = (TextView) findViewById(R.id.emailTv); emailTv1 = (TextView) findViewById(R.id.emailTv1);
         phoneTv = (TextView) findViewById(R.id.phoneTv); phoneTv1 = (TextView) findViewById(R.id.phoneTv1);
         feesTv = (TextView) findViewById(R.id.feesTv); feesTv1 = (TextView) findViewById(R.id.feesTv1);
        
        courseNameTv = (TextView) findViewById(R.id.courseNameTv);
        courseNameTv1 = (TextView) findViewById(R.id.courseNameTv1);
        
        
        mapImg = (ImageView) findViewById(R.id.img_google);
        
        mapImg.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), ComparisonMap.class);
	        	//update.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				i.putExtra("mapData", mapData);
				i.putExtra("startLat", startLat);
				i.putExtra("startLon", startLon);
				i.putExtra("destLat", destLat);
				i.putExtra("destLon", destLon);
				
				i.putExtra("uniName", s.getUniName());
				i.putExtra("schoolName", s.getSchoolName());
				i.putExtra("startAddress", address);
				
	        	startActivity(i);
				
			}
        	
        });
        
        mapImg1 = (ImageView) findViewById(R.id.img_google1);
        
        mapImg1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), ComparisonMap.class);
	        	//update.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				i.putExtra("mapData", mapData1);
				i.putExtra("startLat", startLat);
				i.putExtra("startLon", startLon);
				i.putExtra("destLat", destLat1);
				i.putExtra("destLon", destLon1);
				
				i.putExtra("uniName", s1.getUniName());
				i.putExtra("schoolName", s1.getSchoolName());
				i.putExtra("startAddress", address);
				
	        	startActivity(i);
			}
        	
        });
        
        
        Bundle b = getIntent().getExtras();
        
        // set Course names
        courseName = b.getString("courseName");
        courseName1 = b.getString("courseName1");
        
        courseNameTv.setText(courseName);
        courseNameTv1.setText(courseName1);
        
        new DisplayCourseInfo().execute();
        
        // Initializing
        markerPoints = new ArrayList<LatLng>();
 
        address = b.getString("address");
        if(address.equals("") || address==null)
		{
        	
        	mapContainer.setVisibility(View.GONE);
        	
        	travelTv.setVisibility(View.GONE);
        	travel.setVisibility(View.GONE);
        	travel1.setVisibility(View.GONE);
        	travel2.setVisibility(View.GONE);
        	
		}
        else
        {
        	new DisplayMapInfo().execute();
        }
       
	}
	
	private class DisplayCourseInfo extends AsyncTask<String, String, String> 
	{

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ComparisonResultActivity.this);
			pDialog.setMessage("Loading Course Info..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) 
		{ 
			CourseFunctions cf = new CourseFunctions();
			try {
				c = cf.getCourse(courseName);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				c1 = cf.getCourse(courseName1);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			SchoolFunction c = new SchoolFunction();
			
			s = c.getSchCoordByCourseName(courseName);
			dest = s.getCoord();
			destLat=s.getLat();
			destLon=s.getLon();
			
			s1 = c.getSchCoordByCourseName(courseName1);
			dest1 = s1.getCoord();
			destLat1=s1.getLat();
			destLon1=s1.getLon();
			
			
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() 
				{
					Log.d("","courseName: " + courseName);
					Log.d("","courseName1: " + courseName1);
					String html;	
					
					courseNameTv.setText(c.getCourseName()); courseNameTv1.setText(c1.getCourseName());
				    uniTv.setText(c.getUniName()); uniTv1.setText(c1.getUniName());
				    
				    c.setEntryRecq(c.getEntryRecq().replace(";", "\n"));
				    entryRecqTv.setText(c.getEntryRecq());
				    
				    c1.setEntryRecq(c1.getEntryRecq().replace(";", "\n"));
				    entryRecqTv1.setText(c1.getEntryRecq());

				    
				    adminScheduleTv.setText(c.getAdminSchedule()); adminScheduleTv1.setText(c1.getAdminSchedule());
				    cutOffGpaTv.setText(c.getCutOffGpa()); cutOffGpaTv1.setText(c1.getCutOffGpa());
				    gpaPercTv.setText(c.getGpaPerc()); gpaPercTv1.setText(c1.getGpaPerc());
				    lengthTv.setText(c.getLength()); lengthTv1.setText(c1.getLength());
				    
				    phoneTv.setText(c.getPhone()); phoneTv1.setText(c1.getPhone());
				    schoolTv.setText(s.getSchoolName()); schoolTv1.setText(s1.getSchoolName());
				    
				    scholarshipTv.setText(c.getScholarship()); scholarshipTv1.setText(c1.getScholarship());
				    emailTv.setText(c.getEmail()); emailTv1.setText(c1.getEmail());
			     	feesTv.setText(c.getFees()); feesTv1.setText(c1.getFees());
			     	
				}
			});

		}

	}
	
	private class DisplayMapInfo extends AsyncTask<String, String, String> 
	{

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			/*
			pDialog = new ProgressDialog(ComparisonResultActivity.this);
			pDialog.setMessage("Loading Map Info..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			*/
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) 
		{ 

			Log.d("","s: "+s.getLat() + " " + s.getLon());
			Log.d("","s: "+s1.getLat() + " " + s1.getLon());

			double lat = 0;
			double lon= 0;
			if (address.equals("usecurrentlocation"))
			{
				LocationManager lc =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
				Criteria criteria = new Criteria();
				String provider = lc.getBestProvider(criteria, true);
		        Location loc = lc.getLastKnownLocation(provider);
		        lat = loc.getLatitude();
		        lon = loc.getLongitude();
			}
			else
			{
				Geocoder geocoder = new Geocoder(getApplicationContext());  
				List<Address> addresses = null;
				try {
					addresses = geocoder.getFromLocationName(address, 1);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if(addresses.size() > 0) {
				    lat = addresses.get(0).getLatitude();
				    lon = addresses.get(0).getLongitude();
				}
			}
			startLat=lat;
			startLon=lon;
			
			
			start = new LatLng(lat,lon);

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			//pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() 
				{
					showPoints(dest, 0);
					showPoints(dest1, 1);
				}
			});

		}

	}
	
	private void showPoints(LatLng dest, int seq)
	{	
        // Getting URL to the Google Directions API
        String url = getDirectionsUrl(start, dest);

        DownloadTask downloadTask = new DownloadTask();

        // Start downloading json data from Google Directions API
        downloadTask.execute(url, seq);
	}
	
    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<Object, Void, String>{
 
        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(Object... url) {
 
            // For storing data from web service
            String data = "";
 
            try{
                // Fetching the data from web service
                data = downloadUrl((String)url[0]);
                Log.d("Integer", "Inter:" + ((Integer)url[1]));
                if(((Integer)url[1])==0)
                {
                	mapData = data;
                }
                else
                {
                	mapData1 = data;
                }
            }catch(Exception e){
                Log.d("Background Task",e.toString());
                
            }
            return data;
        }
 
        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
 
            ParserTask parserTask = new ParserTask();
 
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    private String getDirectionsUrl(LatLng origin,LatLng dest){
 
        // Origin of route
        //String str_origin = "origin="+origin.latitude+","+origin.longitude;
    	String str_origin = "origin="+origin.latitude+","+origin.longitude;
        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;
 
        // Sensor enabled
        String sensor = "sensor=false";
        
        // Mode of Direction
        String mode = "mode=transit";
        
        String time = "departure_time=1346197500";
 
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+mode+"&"+time;
 
        // Output format
        String output = "json";
 
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
        
        return url;
    }
 
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
 
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
 
            // Connecting to url
            urlConnection.connect();
 
            // Reading data from url
            iStream = urlConnection.getInputStream();
 
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
 
            StringBuffer sb  = new StringBuffer();
 
            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
 
            data = sb.toString();
 
            br.close();
 
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
  
    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >
    {
 
        // Parsing the data in non-ui thread
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
 
            JSONObject jObject;
            List<List<HashMap<String, String>>> routes = null;
 
            try{
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();
 
                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }
 
        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) 
        {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            String distance = "";
            String duration = "";
 
            if(result.size()<1){
                Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
                return;
            }
 
            // Traversing through all the routes
            for(int i=0;i<result.size();i++)
            {
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();
 
                // Fetching i-th route
                List<HashMap<String, String>> path = result.get(i);
 
                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);
 
                    if(j==0){    // Get distance from the list
                        distance = (String)point.get("distance");
                        continue;
                    }else if(j==1){ // Get duration from the list
                        duration = (String)point.get("duration");
                        continue;
                    }
 
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
 
                    points.add(position);
                }
 
                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(2);
                lineOptions.color(Color.RED);
            }
 
            TextView dist, time;
            GoogleMap m;
           	PolylineOptions p;
            if (seq==0)
            {
            	dist = distanceTv;
            	time = timeTV;
            	//m = map;
            	p = polylineOptions;
            	seq++;
            	
            }
            else
            {
            	dist = distanceTv1;
            	time = timeTV1;
            	//m = map1;
            	p = polylineOptions1;
            }
            
            dist.setText(distance);
            time.setText(duration);
 
            // Drawing polyline in the Google Map for the i-th route
            //m.addPolyline(lineOptions);      
        }
    }


    
    @Override
    public void onLocationChanged(Location location) {
            double lat=(int) (location.getLatitude());
            double lon=(int) (location.getLongitude());
            //latitudeval.setText(String.valueOf(lat));
            //longitudeval.setText(String.valueOf(lon));
            curLoc = new LatLng(lat,lon);
    }


	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
    
    
 

}
